<template>
  <div class="login">
    <Card class="login__panel" dis-hover>
      <p slot="title">{{ $consts.TITLE }}</p>
      <Form
        class="login__form"
        ref="form"
        :model="form"
        :rules="rules"
        :label-width="0"
        label-position="left"
      >
        <Form-item prop="login" :error="error.login">
          <Input
            v-model="form.login"
            size="large"
            prefix="md-person"
            placeholder="请输入用户名或者邮箱"
            @on-enter="handleLogin"
          />
        </Form-item>
        <Form-item prop="password" :error="error.password">
          <Input
            v-model="form.password"
            type="password"
            size="large"
            prefix="md-lock"
            placeholder="请输入密码"
            @on-enter="handleLogin"
          />
        </Form-item>
        <Form-item>
          <Button type="primary" size="large" long @click="handleLogin">登录</Button>
        </Form-item>
      </Form>
    </Card>
  </div>
</template>

<script>
import { mapActions } from 'vuex';

export default {
  data () {
    return {
      form: {
        login: '',
        password: ''
      },
      rules: {
        login: [{ required: true, message: '账号不能为空' }],
        password: [{ required: true, message: '密码不能为空'}]
      },
      error: {
        login: '',
        password: ''
      }
    };
  },

  methods: {
    ...mapActions({
      doLogin: 'doLogin',
      getUserInfo: 'getUserInfo',
    }),
    handleLogin () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.doLogin({
            ...this.form
          }).then(res => {
            if (res.ok) {
              this.$auth.login(res.data);
              this.$store.commit('SET_TOKEN', res.data);
              this.$Message.success('登录成功');
              this.$router.push(this.$route.query.redirect || '/');
              this.getUserInfo();
            } else {
              if (res.msg === 'validate-error') {
                Object.keys(res.data).forEach(key => {
                  this.error[key] = Math.random().toString();
                  this.$nextTick(() => {
                    this.error[key] = res.data[key];
                  });
                });
              } else {
                this.error.password = Math.random().toString();
                this.$nextTick(() => {
                  this.error.password = res.msg;
                });
              }
            }
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.login {
  position: absolute;
  height: 100%;
  width: 100%;
  background-image: url("../../images/login-bg.jpg");
  background-size: cover;
  background-position: center;
  &__panel {
    position: absolute !important;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background-color: white;
    width: 320px;
  }

  &__form {
    margin: 10px 0;
  }
}
</style>
